import React from 'react';
import { inject, observer } from 'mobx-react';
import { withRouter, Route, Link } from 'react-router-dom';
import { Icon,Tools,ActionSheet} from 'weaver-mobile';
import TaskPage from './page';
import TaskPath from './browser'
import TaskViewPath from './path/path'
import { TabPage,RouteLayout  } from 'weaver-mobile-page';
import * as Common from '../../../utils/common';
import renderNoRight from '../../../utils/renderNoRight';
import classnames from 'classnames';
import SuspendButton from 'suspend-button';
import {isMobile} from "../../../utils/mobileDetect";
import './index.less';
const { getLabel } = Tools;
const ButtonGroup = RouteLayout.ButtonGroup;
const hideIcon = "";
const showIcon = "";

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
@inject('edcTaskViewStore', 'browserAllBrowserStore')
@withRouter
@observer
export default class TaskView extends React.Component {
  susButton;
  componentDidMount() {
    const { edcTaskViewStore: store, location: { query,search },browserAllBrowserStore } = this.props;
    
  window.susButton = this.susButton;
    window.browserAllBrowserStore = browserAllBrowserStore;
    if(search){
      let ps = search.substring(1).split("&");
      const params = {};
      for(let i = 0 ; i < ps.length; i++) {
        let p = ps[i].split("=");
        if(p.length > 1)
          params[p[0]] = p[1]
      }

      store.init(params);
    }
}
    switchPcLayout() {
      // if (!window.e9mobileConfig) {
      //   window.e9mobileConfig = {
      //     orientation: 2, // 0 竖屏 1 横屏 2 跟随
      //   }
      // } 
      // if(window.e9mobileConfig.orientation == 0) {
      //   window.e9mobileConfig.orientation = 2;
      // } else {
      //   window.e9mobileConfig.orientation = 0;
      // }
      if(window.em) {
        window.em.getOrientation({
          success: function (res) {
           const corientation = res.orientation === 0 ? 1 : 0;
          window.em.changeOrientation({
            orientation:corientation, // 0,竖屏(默认)，1，横屏，2，跟随屏幕转动
            success: function (res) {
            }
        });
          }
      });
        
      }
      
    }


    resetCollect = () => {

      Common.showConfirm({
          title: getLabel('510797','覆盖'),
          content: <span>
            {getLabel('510798','你已保存过数据，若获取最新数据，')}
            <br/>
            <span style={{color:'#f5222d'}}>{getLabel(504079, '其对应的数据也会被清除，并无法恢复')}</span>。
            <br />
            {getLabel('510799','你确定要覆盖吗？')}
          </span>,
          okEvent: () => {
              const { edcTaskViewStore: store} = this.props;
              store.resetCollect(store.params);
          }
        });
  }

  undo = ()=>{
    const { edcTaskViewStore: store} = this.props;
    store.undo(store.params);
}

    switchTab = (tab) => {
         const { edcTaskViewStore} = this.props;
        // const { comSetStoreState } = wfCommunicateStore;
        // const nowTabKey = wfGlobalStore.tabKey;
        edcTaskViewStore.setTabKey(tab.id);
        // comSetStoreState({
        //     relatedPage: 1, 
        //     page: "allCommunications", 
        //     placeholderValue: getLabel(512567, '交流内容...')
        // });
        // FormUtil.tabChangTriggerEvent(tab.id,nowTabKey);
    }
    getPage(selectedTab, tabs) {
        let page = 0;
        tabs.map ( (item, index) => {
          if(item.id == selectedTab) {
            page = index;
          }
        })
        return page;
      }

      renderContent(tab) {
        console.log(tab,"底部按钮")
      }
      
      forcedCollect = () => {
        const { edcTaskViewStore: store, location: { query } } = this.props;
        store.forcedCollect(store.params);
    }

      issue = () => {
        const { history,browserAllBrowserStore} = this.props;
        history.push(browserAllBrowserStore.browserHrm1.path);
      }
      showActionSheet = (BUTTONS) => {
        BUTTONS.push({
          content: getLabel(31129, '取消'),
          onClick: () => console.log('Cancel'),
        });
        ActionSheet.showActionSheetWithOptions({
          options: BUTTONS,
          cancelButtonIndex: BUTTONS.length - 1,
          // destructiveButtonIndex: BUTTONS.length - 2,
          // title: 'title',
          // message: 'I am description, description, description',
          maskClosable: true,
          'data-seed': 'logId',
          wrapProps,
        },
        (buttonIndex) => {
          this.setState({ clicked: BUTTONS[buttonIndex] });
        });
      }
      getAllButtons = () => {
        const { edcTaskViewStore: store } = this.props;
        const menu = [];
        if(store.canSubmit && store.task.hasSaveBtn) 
            menu.push({
                key: '1',
                icon: 'blog-yiguanzhu',
                content: getLabel(30986, '保存'),
                key: 'save',
                title: getLabel(30986, '保存'),
                flex: 12,
                onClick: store.save,
                disabled:store.loading
            });
        if(store.canSubmit)
            menu.push({
                key: '2',
                icon: 'blog-complete',
                content: getLabel(502502, '提交'),
                key: 'submit',
                title: getLabel(502502, '提交'),
                flex: 12,
                onClick: store.submit,
                disabled:store.loading
            });
        if(store.canSubmit && store.task.hasDistributeBtn)
            menu.push({
                key: '3',
                icon: 'forward-mail',
                content: getLabel('33694', '分发'),
                key: 'fenfa',
                title: getLabel('33694', '分发'),
                flex: 12,
                onClick: ()=>this.issue(),
                disabled:store.loading 
            });
        if(store.canSubmit && store.hasChild && store.task.hasCoverBtn)
            menu.push({
                key: '4',
                icon: 'flow',
                content: getLabel('510797','覆盖'),
                key: 'fugai',
                title: getLabel('510797','覆盖'),
                flex: 12,
                onClick: ()=>this.resetCollect(),
                disabled:store.loading 
            });
        if (store.canUndo && store.task.hasUndoBtn)
            menu.push({
                key: '5',
                icon: 'refresh',
                content: getLabel('32025','撤回'),
                key: 'chehui',
                title: getLabel('32025','撤回'),
                flex: 12,
                onClick: ()=>this.undo,
                disabled:store.loading 
            })
        if (store.reportType && !store.canSubmit && store.task.hasCollectBtn)
            menu.push({
                key: '6',
                icon: 'organization',
                content: getLabel('510796','强制收集'),
                key: 'shouji',
                title: getLabel('510796','强制收集'),
                flex: 12,
                onClick: this.forcedCollect,
                disabled:store.loading 
            })
            // 移动端导出有点问题，先隐藏
            if(false)
            menu.push({
              key:'7',
              content:getLabel(502294,'导出'),
              title:getLabel(502294,'导出'),
              key:'daochu',
              flex: 12,
              onClick: store.exportExcel,
              disabled:store.loading
            })
        return menu;
    }


    getButtonGroupData = () => {
      const buttonGroupData =[];
      const actionSheet =[];
      const buttonGroup = this.getAllButtons();
      if(buttonGroup.length == 0) {
        return buttonGroupData;
      } else if (buttonGroup.length <= 2) {
        return buttonGroup;
      }else {
        for (let i = 0 ; i < buttonGroup.length; i++) {
          if(i <=1) {
            buttonGroupData.push(buttonGroup[i]);
          } else {
            actionSheet.push(buttonGroup[i]);
          }
          
        }
        buttonGroupData.push({
          key: 'more',
          title: '更多',
          flex: 6,
          disabled: false,
          onClick: () => this.showActionSheet(actionSheet),
        })
        return buttonGroupData;
      }


    }

    render() {
        const { edcTaskViewStore, browserAllBrowserStore : browserStore} = this.props;
        const {selectedTab} = edcTaskViewStore;
        console.log(edcTaskViewStore.ismobile,"edcTaskViewStore.ismobile");
        if (edcTaskViewStore.excel.isRight !== undefined && !edcTaskViewStore.excel.isRight) {
          return renderNoRight();
      }
        const buttonGroupData2 = this.getButtonGroupData();

        const tabs = edcTaskViewStore.tabs;

        let tabBtns = [<div className="wf-req-switch-pc" onClick={this.switchPcLayout.bind(this)}>
        <Icon type={"pc"} />
    </div>];
        // tabBtns.push([
        //     <div className="wf-req-switch-pc" onClick={this.switchPcLayout.bind(this)}>
        //         <Icon type={"pc"} />
        //     </div>
        // ]);

        const tabProps = {
            onTabClick: (tab) => {
               this.switchTab(tab);
               //comSetStoreState({needPanel: false});
            },
            onChange: (tab) => {
                console.log('onChange:', tab);
                edcTaskViewStore.onChangeTab(tab.key)
              },
          };

        return (
          
            // <div className="wf-req">
            <div className="edc-task-view">
                {edcTaskViewStore.showButtons && <div className="wf-req-top">
                <TabPage
                        tabs={tabs}
                        btns={window.em ? tabBtns : []} 
                        span={2} 
                        tabProps={tabProps} 
                        //popover popoverProps={popoverProps}
                    />
                </div>}
                <div className={classnames("edc-task-view-content",`${edcTaskViewStore.showButtons ? (buttonGroupData2 && (buttonGroupData2.length > 0)) ?  'edc-task-view-content-notall' : 'edc-task-view-content-all' : 'edc-task-view-content-nobuttons'}`)}>
                {<TaskPage store={edcTaskViewStore} browserStore={browserStore}></TaskPage>}
                    
                    {edcTaskViewStore.selectedTab === 'path' && <TaskViewPath store={edcTaskViewStore}/>}
                </div>
                <div style ={{display : 'none'}}>
                {<TaskPath store={edcTaskViewStore}></TaskPath>}
                  </div>
                {/* <ViewButtons data={buttons}></ViewButtons> */}
                {buttonGroupData2 && (buttonGroupData2.length > 0 ) && edcTaskViewStore.showButtons && <ButtonGroup data={buttonGroupData2} isButton={false} />}
                {isMobile() && 
                <SuspendButton 
                onClick ={edcTaskViewStore.changeShowButtons} 
                img={edcTaskViewStore.showButtons ? hideIcon : showIcon}
                ref={ref => this.susButton = ref}
                >

                </SuspendButton>}
                </div>
                
        
                // </div>
        )
        
    }

}
